package com.kuang.dao.impl;

import com.kuang.dao.EmployeeDao;
import com.kuang.pojo.Department;
import com.kuang.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

@Component
@Service
public class EmployeeDaoImpl implements EmployeeDao {

    @Autowired
    private DepartmentDaoImpl departmentDaoImpl;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void save(Employee employee) {

        String sql = "insert into employee (last_name, email, gender, department_id, birth) values (?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql, employee.getLastName(), employee.getEmail(), employee.getGender(), employee.getDepartment().getId(), employee.getBirth());

    }

    @Override
    public Collection<Employee> getAll() {
        Collection<Employee> employees = new ArrayList<>();

        String sql = "select * from employee";
        List<Map<String, Object>> lists = jdbcTemplate.queryForList(sql);
        for(Map<String, Object> list : lists) {
            Integer id = (Integer) list.get("id");
            Employee employee = getEmployeeById(id);
            employees.add(employee);
        }

        return employees;
    }

    @Override
    public Employee getEmployeeById(Integer id) {
        String sql = "select * from employee where id=?";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, id);

        // 将数据库的数据映射为实体类
        // 获取数据库字段
        String lastName = (String) map.get("last_name");
        String email = (String) map.get("email");
        Integer gender = (Integer) map.get("gender");
        String birth = (String) map.get("birth");
        Integer deptId = (Integer) map.get("department_id");
        Date entryTime = (Date) map.get("entry_time");

        // 通过获取到的数据实例化实体类
        Employee employee = new Employee();
        employee.setId(id);
        employee.setLastName(lastName);
        employee.setEmail(email);
        employee.setGender(gender);
        employee.setBirth(birth);
        employee.setDepartment(departmentDaoImpl.getDepartmentById(deptId));
        employee.setEntryTime(entryTime);

        return employee;
    }

    @Override
    public void removeEmployeeById(Integer id) {
        String sql = "delete from employee where id=?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public Integer updateEmployeeById(Employee employee) {
        String sql = "update employee set last_name=?, email=?, gender=?, department_id=?, birth=? where id=?";
        return jdbcTemplate.update(sql, employee.getLastName(), employee.getEmail(), employee.getGender(), employee.getDepartment().getId(), employee.getBirth(), employee.getId());
    }
}
